<template>
    <div
        style="padding-top: 40px"
        v-loading="pageLoading"
        element-loading-text="正在加载,请稍等"
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
    >
        <div style="margin: 5px 10px 30px 15px">
            <!-- 标题 -->
            <el-row>
                <el-col :span="12">
                    <h2 v-if="signSealStatus === 'NOIDENTITY'" style="color: red; margin-bottom: 15px">
                        您还没有实名认证，请到官网进行实名认证了在进行相应操作
                    </h2>
                </el-col>
            </el-row>

            <!-- 1. 订单信息 -->
            <div>
                <el-row>
                    <el-col :span="12">
                        <h3 class="small-title">订单信息</h3>
                    </el-col>
                </el-row>

                <el-form :model="infoForm" style="margin-top: 15px">
                    <el-row :gutter="30">
                        <el-col :span="6">
                            <el-form-item label="订单号">
                                <el-input v-model="infoForm.id" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="6">
                            <el-form-item label="订单状态">
                                <el-input v-model="infoForm.orderStatus" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="30">
                        <el-col :span="6">
                            <el-form-item label="下单时间">
                                <el-input v-model="infoForm.createTime" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="6">
                            <el-form-item label="订单总金额">
                                <el-input v-model="infoForm.totalMoney" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="30">
                        <el-col :span="6">
                            <el-form-item label="下单人">
                                <el-input v-model="infoForm.userName" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="6">
                            <el-form-item label="下单人电话">
                                <el-input v-model="infoForm.userPhone" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="30">
                        <el-col :span="6">
                            <el-form-item label="供应商">
                                <el-input v-model="infoForm.providerName" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="6">
                            <el-form-item label="供应商电话">
                                <el-input v-model="infoForm.providerPhone" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <!-- 2.产品信息 -->
            <div>
                <el-row>
                    <el-col :span="12">
                        <h3 class="small-title">产品信息</h3>
                    </el-col>
                </el-row>

                <el-row style="margin: 30px 30px 30px 0px">
                    <el-col :span="18">
                        <TableList
                            tableRef="table"
                            ref="multipleTable"
                            :checkBoxEnable="false"
                            :showPagination="false"
                            :data="cpInfoDataList ? cpInfoDataList : []"
                            :listConfig="cpInfoResultColConfig"
                            :listLoading="cpInfoListLoading"
                        ></TableList>
                    </el-col>
                </el-row>
            </div>

            <!-- 3. 收货人信息 -->
            <div>
                <el-row>
                    <el-col :span="12">
                        <h3 class="small-title">收货人信息</h3>
                    </el-col>
                </el-row>

                <el-form :model="infoForm" style="margin-top: 15px">
                    <el-row :gutter="30">
                        <el-col :span="6">
                            <el-form-item label="收货人姓名">
                                <el-input v-model="infoForm.name" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :span="6">
                            <el-form-item label="收货人电话">
                                <el-input v-model="infoForm.phone" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row :gutter="30">
                        <el-col :span="18">
                            <el-form-item label="收货人地址">
                                <el-input v-model="infoForm.address" placeholder="" :disabled="isEdit"></el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <!-- 4.操作内容 -->
            <div>
                <el-form :model="dataForm" style="margin-top: 15px">
                    <el-row :gutter="30">
                        <el-col :span="18">
                            <el-form-item label="状态">
                                <el-select v-model="baseName" placeholder="请选择" :disabled="baseNameSelectedDis">
                                    <el-option
                                        v-for="(item, index) in baseNameptions"
                                        :key="index"
                                        :label="item.baseName"
                                        :value="item.baseId"
                                    >
                                    </el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-row>

                    <el-row style="margin-bottom: 60px">
                        <!-- 电子签章状态. FINISHED: 已生成,直接使用签章sealData；WAIT: 已实名认证,等待生成签章；NOIDENTITY: 未实名,请先实名认证 -->

                        <div v-if="signSealStatus === 'NOIDENTITY'">
                            <!-- <el-button type="primary" @click="goCertification()">去实名认证</el-button> -->
                        </div>

                        <div v-if="signSealStatus === 'WAIT'">
                            <el-button type="primary" @click="dataFormSubmit(1)">签字</el-button>
                        </div>

                        <div v-if="signSealStatus === 'FINISHED'">
                            <!-- <viewer :images="pageData.signSealStatus.sealData"> -->
                            <img :src="pageData.signSealStatus.sealData" class="viewer_img" />
                            <!-- </viewer> -->
                        </div>

                        <div v-if="signSealStatus === 'FINISHED' && pageData.isSign === 0">
                            <el-button type="primary" @click="dataFormSubmit(2)">签署合同</el-button>
                        </div>
                        <div v-if="signSealStatus === 'FINISHED' && pageData.isSign === 1">
                            <el-button type="primary" :disabled="true">已签署合同</el-button>
                            <el-button type="primary" @click="downFile(pageData.contract)">签署合同下载</el-button>
                        </div>
                    </el-row>
                </el-form>

                <span slot="footer" class="dialog-footer">
                    <el-button type="primary" @click="dataFormSubmit(3)">保存</el-button>
                    <el-button @click="closePage()">取消</el-button>
                </span>
            </div>
        </div>

        <signDialog v-if="signDialogVisible" ref="signDialogDom" @refreshDataList="getPageDeail(this.itemData.id)"></signDialog>

        <realName v-if="realNameVisible" ref="realNameDom" @refreshDataList="getPageDeail(this.itemData.id)"></realName>
    </div>
</template>
<script>
import API from '@/api';
import cloneDeep from 'lodash/cloneDeep';
import TableList from '../../../components/TableList';
import moreUpFile from '../../../components/upLoad/moreUpFile';
import signDialog from './../transactionOrderManager/sign-dialog';
import realName from './../transactionOrderManager/realName';

import { CPINFO_RESULT_ITEMS } from './config';
import { orderStatusType } from '../../../utils/util';

export default {
    components: {
        TableList,
        moreUpFile,
        signDialog,
        realName
    },
    data() {
        return {
            pageLoading: false,
            isEdit: true,

            //- 基础信息
            infoForm: {
                id: '', //订单号
                orderStatus: '', //订单状态
                createTime: '', //下单时间
                totalMoney: '', //订单总金额
                userName: '', //下单人
                userPhone: '', //下单人电话

                providerName: '', //供应商
                providerPhone: '', //供应商电话

                name: '', //收货人姓名
                phone: '', //收货人电话
                address: '' //收货地址
            },

            //- 产品信息
            cpInfoListLoading: false, // 数据列表显示状态
            cpInfoResultColConfig: CPINFO_RESULT_ITEMS,
            cpInfoDataList: [], //  规格数据列表

            dataForm: {
                orderStatus: '', //状态
                contract: '' //上传合同
            },
            contractList: [],
            contractListId: [],
            contractListUrl: [],

            //选择状态
            baseName: '待发货',
            baseNameSelectedDis: false,
            baseNameptions: [
                // { baseId: 0, baseName: '待发货', selected: true }, //(0:待发货;1:已发货)
                { baseId: 1, baseName: '已发货', selected: false }
            ],
            //实名认证
            realNameVisible: false,

            //签字
            signSealStatus: '',
            signDialogVisible: false,

            //签署合同
            isUpdisable: true,

            //- 公用
            itemData: null,
            pageFlag: '',
            pageData: null
        };
    },

    watch: {
        //- 解决 同一页面，数据不刷新问题

        // 监听相同路由下参数变化的时候，从而实现异步刷新
        $route(to, from) {
            this.nickname = this.$route.query.nickname; //修改页面标题
        }
    },

    mounted() {
        this.itemData = this.$route.query.itemData;
        var type = this.$route.query.type;
        if (type == 2) {
            var id = this.itemData.id;

            this.getPageDeail(id); // 获取基本信息
        }

        this.dialogType = type;
    },

    methods: {
        handleClick(tab, event) {
            console.log(tab, event);
        },
        handleClose() {
            this.dataForm = {};
            this.$refs['dataForm'].resetFields();
        },
        // 获取页面详情
        getPageDeail(id) {
            //详情
            var _that = this;
            _that.pageLoading = true;

            let params = {
                id: id
            };

            var tick;
            switch (this.$route.path) {
                case '/transactionManager/publicProductOrderManger/ncp/order-details':
                    //农产品
                    tick = API.transactionManager.getNcpOrderDetails(params);

                    break;

                case '/transactionManager/publicProductOrderManger/nz/order-details':
                    //农资产品

                    tick = API.transactionManager.getNzOrderDetails(params);

                    break;
            }

            //详情
            tick.then((res) => {
                console.log(res);

                _that.pageData = res.result;

                //页面基本信息
                _that.infoForm = _that.pageData;
                //处理订单状态
                _that.pageData.orderStatus = orderStatusType(_that.pageData.orderStatus);
                if(_that.pageData.orderStatus==='已发货'){
                   this.baseName='已发货';
                }
                
                //处理 签字状态
                if (_that.pageData.signSealStatus != null) {
                    _that.signSealStatus = _that.pageData.signSealStatus.status;

                    if (_that.signSealStatus === 'NOIDENTITY') {
                        _that.$message.error('您还没有实名认证，请到官网进行实名认证了在进行相应操作');
                    }

                    //已签署不能在上传
                    if (_that.signSealStatus === 'FINISHED' && _that.pageData.isSign === 1) {
                        _that.isUpdisable = false;
                    }
                }

                //处理 签字图片
                _that.pageData.signSealStatus.sealData = 'data:image/png;base64,' + _that.pageData.signSealStatus.sealData;

                //产品数据
                _that.cpInfoDataList = _that.pageData.res;

                _that.pageLoading = false;
            });
        },

        //获取选择状态
        getBaseNameptions(parm, name) {
            if (this.isChinese(name)) {
                //全是中文，代表用户没有选择，为默认值，或者
                for (var i = 0; i < this.baseNameptions.length; i++) {
                    if (this.baseNameptions[i].baseName === name) {
                        this.dataForm.orderStatus = this.baseNameptions[i].baseId;
                        parm.orderStatus = this.baseNameptions[i].baseId;
                    }
                }
            } else {
                //选择之后，name为代码id
                for (var i = 0; i < this.baseNameptions.length; i++) {
                    if (this.baseNameptions[i].baseId === name) {
                        this.dataForm.orderStatus = this.baseNameptions[i].baseId;
                        parm.orderStatus = this.baseNameptions[i].baseId;
                    }
                }
            }
        },

        //是否全是 中文
        isChinese(temp) {
            var re = /[^\u4e00-\u9fa5]/;
            if (re.test(temp)) return false;
            return true;
        },

        //下载文件
        downFile(downId) {
            var reg = new RegExp('http://');

            if (reg.test(downId)) {
                var idIndex = downId.indexOf('id=');
                var idStr = downId.substring(idIndex, downId.length);

                if (idStr.indexOf('id=') != -1) {
                    window.location.href = window.baseUrl + '/sys/file/new/down?TOKEN=' + sessionStorage.getItem('token') + '&' + idStr;
                }
            } else {
                window.location.href = window.baseUrl + '/sys/file/new/down?TOKEN=' + sessionStorage.getItem('token') + '&id=' + downId;
            }
        },

        //用户操作 :保存
        dataFormSubmit(type) {
            if (type == 1) {
                //签字
                this.signDialogVisible = true;
                var userType = sessionStorage.getItem('userType');
                console.log('获取的用户类型：', userType);
                this.$refs.signDialogDom.init(userType);
            }

            if (type == 2) {
                //签署合同
                let params = {
                    id: this.pageData.id //订单id
                };

                //合同 处理
                if (this.pageData.contract != null && this.pageData.contract !== '') {
                    params.contract = this.pageData.contract;
                } else {
                    this.$message.error('请联系购买方上传合同，上传合同之后才能签署合同');
                    return;
                }

                var tick;

                switch (this.$route.path) {
                    case '/transactionManager/publicProductOrderManger/ncp/order-details':
                        //农产品
                        tick = API.transactionManager.ncpOrderDetails_SignContract(params);

                        break;

                    case '/transactionManager/publicProductOrderManger/nz/order-details':
                        //农资产品

                        tick = API.transactionManager.nzOrderDetails_SignContract(params);

                        break;
                }

                tick.then((data) => {
                    if (data.code == '0000') {
                        this.$message({
                            message: '操作成功',
                            type: 'success',
                            duration: 1500,
                            onClose: () => {
                                this.contractList = [];
                                this.contractListUrl = [];
                                this.getPageDeail(this.itemData.id);
                            }
                        });
                    }
                });
            }

            if (type == 3) {
                //保存
                let params = {
                    id: this.pageData.id
                };
                this.getBaseNameptions(params, this.baseName);

                var tick;
                switch (this.$route.path) {
                    case '/transactionManager/publicProductOrderManger/ncp/order-details':
                        //农产品
                        tick = API.transactionManager.ncpOrderDetailsSave(params);

                        break;

                    case '/transactionManager/publicProductOrderManger/nz/order-details':
                        //农资产品

                        tick = API.transactionManager.nzOrderDetailsSave(params);

                        break;
                }

                //详情
                tick.then((res) => {
                    if (res.code == '0000') {
                        this.$message({
                            message: '操作成功',
                            type: 'success',
                            duration: 1500,
                            onClose: () => {
                                this.closePage();
                            }
                        });
                    }
                });
            }
        },

        closePage() {
            this.$router.go(-1);
        }
    }
};
</script>
<style scoped>
.viewer_img {
    position: relative;
    width: 100px;
    height: 100px;
}
</style>